const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
const { Op } = require('sequelize');

// 获取所有产品
router.get('/', async (req, res) => {
    try {
        const { page = 1, limit = 10, search = '', category = '' } = req.query;
        const offset = (page - 1) * limit;

        const whereClause = {};
        if (search) {
            whereClause[Op.or] = [
                { name: { [Op.like]: `%${search}%` } },
                { description: { [Op.like]: `%${search}%` } }
            ];
        }
        if (category) {
            whereClause.category = category;
        }

        const products = await Product.findAndCountAll({
            where: whereClause,
            limit: parseInt(limit),
            offset: parseInt(offset),
            order: [['updatedAt', 'DESC']]
        });

        res.json({
            products: products.rows,
            total: products.count,
            pages: Math.ceil(products.count / limit),
            currentPage: parseInt(page)
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 获取单个产品
router.get('/:id', async (req, res) => {
    try {
        const product = await Product.findByPk(req.params.id);
        if (!product) {
            return res.status(404).json({ error: '产品未找到' });
        }
        res.json(product);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 获取低库存产品
router.get('/alerts/low-stock', async (req, res) => {
    try {
        const threshold = parseInt(req.query.threshold) || 10;
        const lowStockProducts = await Product.findAll({
            where: {
                stock_quantity: { [Op.lte]: threshold },
                is_active: true
            },
            order: [['stock_quantity', 'ASC']]
        });
        res.json(lowStockProducts);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 更新产品AI描述
router.put('/:id/ai-description', async (req, res) => {
    try {
        const { description } = req.body;
        const product = await Product.findByPk(req.params.id);
        if (!product) {
            return res.status(404).json({ error: '产品未找到' });
        }
        
        product.ai_description = description;
        await product.save();
        
        res.json({ message: 'AI描述已更新', product });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;
